﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using BTAlertWinService.DBOps;
using BTAlertWinService.Models;
using BTAlertWinService.Logging;
using System.IO;
namespace BTAlertWinService
{
    public partial class BTAlertWinService : ServiceBase
    {
        public BTAlertWinService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            BiztalkToAlertDB.Start();
            SendEmail.Start();        
        }

        protected override void OnStop()
        {
            BiztalkToAlertDB.Stop();
            SendEmail.Stop();

        }

 
        private void BiztalkToAlertDB_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            FileLogger.Log("fetchReceiveLocations has started." + DateTime.Now.ToString());
            IList<ReceiveLocations> locations = BTOPerations.fetchReceiveLocations();
            
            List<AReceiveLocations> aLocations = new List<AReceiveLocations>();

            foreach (ReceiveLocations loc in locations)
            {
                AReceiveLocations aLoc = new AReceiveLocations() { ApplicationName = loc.ApplicationName, 
                    LocationName = loc.LocationName, PortName = loc.PortName,
                    PortDisabled = loc.PortDisabled, type = "Receive"
                };
                aLocations.Add(aLoc);
            }


            FileLogger.Log("fetchReceiveLocations has Successful." + DateTime.Now.ToString());
            FileLogger.Log("InsertReceiveLocations has Started." + DateTime.Now.ToString());
            BTAlertOperations.InsertReceiveLocations(aLocations);
            FileLogger.Log("InsertReceiveLocations has Successful." + DateTime.Now.ToString());

            IList<SendLoctions> sendLocations = BTOPerations.fetchSendLocations();
            List<ASendLoctions> sLocations = new List<ASendLoctions>();

            foreach (SendLoctions loc in sendLocations)
            {
                ASendLoctions aLoc = new ASendLoctions()
                {
                    ApplicationName = loc.ApplicationName,
                    LocationName = loc.LocationName,
                    PortName = "",
                    PortDisabled = (loc.PortStatus == "Stopped" || loc.PortStatus == "UnEnlisted")? true :false,
                    type = "Send"
                };
                sLocations.Add(aLoc);
            }


            FileLogger.Log("fetchSendeLocations has Successful." + DateTime.Now.ToString());
            FileLogger.Log("InsertSendLocations has Started." + DateTime.Now.ToString());
            BTAlertOperations.InsertSendLocations(sLocations);
            FileLogger.Log("InsertReceiveLocations has Successful." + DateTime.Now.ToString());
        }

        private void SendEmail_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            FileLogger.Log("fetchNewAlerts has started." + DateTime.Now.ToString());

            IList<AAlerts> alerts = BTAlertOperations.fetchNewAlerts();
            List<string> Locations = new List<string>();

            FileLogger.Log("fetchNewAlerts has Successful." + DateTime.Now.ToString());
            List<string> toList = new List<string>();
            foreach (AAlerts alert in alerts)
            {
                if (alert.PrimaryEmail != string.Empty)
                toList.Add(alert.PrimaryEmail);
                if (alert.SecondaryEmail != string.Empty)
                toList.Add(alert.SecondaryEmail);
                if (alert.Others != string.Empty)
                toList.Add(alert.Others);
                Locations.Add(alert.LocationName);                

                //send email 
                if (MailComponent.SendEmail(createEmailBody("Biztalk Owner", "Receive Location Down :", GetStringAsMyTable(Locations)), "Critical Alert", toList))
                    // upadte db 
                    BTAlertOperations.UpdateLocationMonitor(alert.LocationName,  alert.type);
            }
            FileLogger.Log("UpdateLocationMonitor has Successful." + DateTime.Now.ToString());
            
            
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            FileLogger.Log("fetchNewAlerts has started." + DateTime.Now.ToString());

            IList<downTimeReporting> downTimes = BTAlertOperations.fetchDownTime(System.Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DownTimeDurationInms"]));
            FileLogger.Log("fetchNewAlerts has Successful." + DateTime.Now.ToString());
            List<string> toList = new List<string>();

            if (downTimes.Count >= 1)
            {
                var htmlTable = GetMyTable(downTimes);
                FileLogger.Log("MailComponent has Started" + DateTime.Now.ToString());
                toList.Add(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["BiztalkTeamMailID"]));
                MailComponent.SendEmail(createEmailBody("Integration Owner", "DownTime Details", htmlTable), "Receive Location DownTime Details", toList);
                FileLogger.Log("MailComponent has Succesful" + DateTime.Now.ToString());
            }
            FileLogger.Log("UpdateLocationMonitor has Successful." + DateTime.Now.ToString());
            
            
        }


        private string createEmailBody(string userName, string title, string message)
        {

            string body = string.Empty;
            //using streamreader for reading my htmltemplate               
            using (StreamReader reader = new StreamReader(System.IO.Path.Combine(
                System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "HtmlTemplate.html")))
            {

                body = reader.ReadToEnd();

            }

            body = body.Replace("{UserName}", userName); //replacing the required things  

            body = body.Replace("{Title}", title);

            body = body.Replace("{message}", message);

            return body;

        }

        private string GetStringAsMyTable(IList<string> dtReportings)
        {
            StringBuilder html = new StringBuilder();
            html.Append("<table border = '1'>");

            //Building the Header row.
            html.Append("<tr>");

            html.Append("<th>");
            html.Append("Receive Location Name");
            html.Append("</th>");
            

            html.Append("</tr>");

            //Building the Data rows.
            foreach (string row in dtReportings)
            {
                html.Append("<tr>");

                html.Append("<td>");
                html.Append(row);
                html.Append("</td>");

                html.Append("</tr>");
            }

            //Table end.
            html.Append("</table>");


            return html.ToString();
        }

        private  string GetMyTable(IList<downTimeReporting> dtReportings)
        {
            StringBuilder html = new StringBuilder();
            html.Append("<table border = '1'>");

            //Building the Header row.
            html.Append("<tr>");
            
            html.Append("<th>");
            html.Append("Receive Location Name" );
            html.Append("</th>");

            html.Append("<th>");
            html.Append("DownTime in Hours");
            html.Append("</th>");

            html.Append("</tr>");

            //Building the Data rows.
            foreach (downTimeReporting row in dtReportings)
            {
                html.Append("<tr>");                
                
                html.Append("<td>");
                html.Append(row.LocationName);
                html.Append("</td>");

                html.Append("<td>");
                html.Append(row.DownTime);
                html.Append("</td>");
            

                html.Append("</tr>");
            }

            //Table end.
            html.Append("</table>");


            return html.ToString();
        }

    }
}
